package com.auth.assembler;

import com.auth.entity.dao.User;
import com.auth.entity.dto.AuthorityDto;
import com.auth.entity.dto.RoleDto;
import com.auth.entity.dto.UserAuthorityDto;
import com.auth.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 大忽悠
 * @create 2023/2/14 15:10
 */
@RequiredArgsConstructor
@Component
public class UserAssembler {
   private final IUserService iUserService;
   private final IUserRoleService iUserRoleService;
   private final IRoleAuthorityService iRoleAuthorityService;

    public UserAuthorityDto getUserAuthorities(String username, String serviceName) {
        UserAuthorityDto.UserAuthorityDtoBuilder authorityDtoBuilder = UserAuthorityDto.builder();
        //1.用户是否存在,是否启用了用户
        User user = iUserService.getOne(new QueryWrapper<User>().eq("username", username).eq("service_name", serviceName));
        if(user==null || user.getEnabled()!=1){
            return authorityDtoBuilder.legal(false).build();
        }
        List<String> authorities=new ArrayList<>();
        //2.查询用户用户的角色列表
        List<RoleDto> roleDtoList = iUserRoleService.getRoleOfUser(user.getId());
        //3.查询每个角色拥有的权限集合,并进行汇总
        roleDtoList.stream()
                //跳过被禁用的角色
                .filter(roleDto -> roleDto.getEnabled()==1)
                //跳过被禁用的权限
                .map(roleDto -> iRoleAuthorityService.getAuthorityOfRole(roleDto.getId()).stream()
                        .filter(authorityDto -> authorityDto.getEnabled()==1)
                        .map(AuthorityDto::getName)
                        .collect(Collectors.toList()))
                //汇总权限信息
                .forEach(authorities::addAll);
        return authorityDtoBuilder.legal(true).authorities(authorities).build();
    }
}
